from PyQt5 import QtGui
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QPixmap
import cv2


class ImageViewer:
    def __init__(self, label_qian, label_hou):
        self.label_qian = label_qian
        self.label_hou = label_hou
        self.cascade_classifier = cv2.CascadeClassifier(
            'D:/Programming_Softwares/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')

    def load_image(self, file_path):
        image = cv2.imread(file_path)
        if image is not None:
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            faces = self.cascade_classifier.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
            for (x, y, w, h) in faces:
                cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            image = cv2.resize(image, (300, 300))
            image = QImage(image.data, image.shape[1], image.shape[0], QImage.Format_RGB888)
            pixmap = QPixmap.fromImage(image)
            # 在self.label_qian显示原照片
            self.label_qian.setPixmap(QtGui.QPixmap(file_path))
            self.label_qian.setScaledContents(True)
            # 在self.label_hou显示处理后的照片
            self.label_hou.setPixmap(pixmap.scaled(self.label_qian.size(), Qt.KeepAspectRatio))
            self.label_hou.setScaledContents(True)
        else:
            QMessageBox.warning(None, '错误', '无法加载图片', QMessageBox.Ok)
